/*
 * Copyright 2010 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal.persistence;

import java.util.ArrayList;
import java.util.List;

import org.shalma.persistence.PersistenceException;
import org.shalma.persistence.Translator;

public class ListTranslator implements Translator<List<?>, List<?>> {

	private static final String TYPE_ID = "$List";

	private static final String VOID = "";

	@Override
	public String getTypeId() {
		return TYPE_ID;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<?> toType(List<?> list) {

		TranslatorManager mapper = getMapper();
		ArrayList<Object> result = new ArrayList<Object>(list.size());

		String lastTypeId = null;
		Translator translator = null;

		for (int index = 0; index < list.size(); index++) {

			String typeId = (String) list.get(index++);
			if (!typeId.equals(VOID))
				translator = mapper.getTranslator(typeId);

			Object property = list.get(index);
			result.add(translator.toType(property));
		}

		return result;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List<?> toProperty(List<?> list) {

		if (list.isEmpty())
			return list;

		TranslatorManager mapper = getMapper();
		ArrayList<Object> result = new ArrayList<Object>();

		Class<? extends Object> lastType = null;
		Translator translator = null;

		for (Object property : list) {

			Class<? extends Object> type = property.getClass();
			if (type.equals(lastType))
				result.add(VOID);
			else {
				lastType = type;
				translator = mapper.getTranslator(type);
				if (translator == null)
					throw new PersistenceException(type, "Translator not found");
				result.add(translator.getTypeId());
			}

			result.add(translator.toProperty(property));
		}

		return result;
	}

	private TranslatorManager getMapper() {
		return null;
	}
}
